package xiaoqi.springwebsockt.handler;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import xiaoqi.springwebsockt.message.AuthRequest;
import xiaoqi.springwebsockt.message.AuthResponse;
import xiaoqi.springwebsockt.message.UserJoinNoticeRequest;
import xiaoqi.springwebsockt.util.WebSocketUtil;

import javax.websocket.Session;

@Component
public class AuthMessageHandler implements MessageHandler<AuthRequest> {

    @Override
    public void execute(Session session, AuthRequest message) {
        if(StringUtils.isEmpty(message.getAccessToken())) {
            WebSocketUtil.send(session, AuthRequest.TYPE,
                    new AuthResponse().setCode(1).setMessage("认证 accessToken 未传入"));
            return;
        }
        WebSocketUtil.addSession(session, message.getAccessToken());
        WebSocketUtil.send(session, AuthResponse.TYPE,
                new AuthResponse().setCode(0));
        WebSocketUtil.broadcast(UserJoinNoticeRequest.TYPE,
                new UserJoinNoticeRequest().setNickname(message.getAccessToken()));
     }

    @Override
    public String getType() {
        return AuthRequest.TYPE;
    }
}
